<template>
  <div class="main">
    <mine-title>新建选项</mine-title>
    <div class="content" v-loading="loading">
      <el-row :gutter="20">
        <el-col :span="12">
          <div>
            <el-form
              ref="form"
              :model="form"
              label-width="110px"
              :rules="rules"
            >
              <el-form-item label="选项编码：" prop="optCode">
                <el-input
                  v-model="form.optCode"
                  size="small"
                  clearable
                ></el-input>
              </el-form-item>
              <el-form-item label="选项名称：" prop="optName">
                <el-input
                  v-model="form.optName"
                  size="small"
                  clearable
                ></el-input>
              </el-form-item>
              <el-form-item label="描述：" prop="description">
                <el-input
                  type="textarea"
                  v-model="form.description"
                  autosize
                ></el-input>
              </el-form-item>
              <el-form-item label="排序码：" prop="number">
                <el-input-number
                  v-model="form.number"
                  autosize
                ></el-input-number>
              </el-form-item>
              <el-form-item class="form-btn-row">
                <mine-button type="primary" @click="onCancel" secondary
                  >取 消</mine-button
                >
                <mine-button type="primary" @click="onSubmit"
                  >保 存</mine-button
                >
              </el-form-item>
            </el-form>
          </div>
        </el-col>
        <el-col :span="12"> </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import request from "@/modules/index/utils/request";
import { QWebChannel } from "@/modules/index/utils/qwebchannel.js";
export default {
  name: "addOption",
  data() {
    return {
      form: {
        className: null,
        description: "",
        dirId: "",
        id: 0,
        methodName: null,
        number: 0,
        optCode: "",
        optName: "",
      },
      rules: {
        optCode: [
          {
            required: true,
            message: "请填写字典编码",
            trigger: "blur",
          },
        ],
        optName: [
          {
            required: true,
            message: "请填写字典名称",
            trigger: "blur",
          },
        ],
      },
      loading: false,
    };
  },
  computed: {},
  methods: {
    onSubmit() {
      let _this = this;
      this.$refs.form.validate(async (valid, object) => {
        let { form } = _this;
        if (valid) {
          // console.log(form);
          this.loading = true;
          let res = {};
          let _self = this;
          if (_self.$qwebUtil.isQtClient) {
            const uuid = _self.$qwebUtil.generateRandomUUID();
            let sendObject;
            /* eslint-disable-next-line */
            const channel = new QWebChannel(
              window.qt.webChannelTransport,
              async function (channel) {
                sendObject = channel.objects.sendObject;
                // receivedJSON 修改此处发送请求参数
                const receivedJSON = {
                  RequestUrl: "/dictionaryParam/save",
                  RequestMethod: "post",
                  ContentType: "application/json;charset=UTF-8",
                  RequestBody: form,
                  isStringParam: false,
                  requestId: uuid,
                };
                await send();
                await _self.$qwebUtil.receive(sendObject, receivedJSON);
                // console.error('received','/feCanvas/pageList')
              }
            );
            /* eslint-disable-next-line */
            async function send() {
              sendObject.sendMessage.connect(function (data) {
                if (!data) {
                  console.error("No data received.");
                }
                res = JSON.parse(data);
                const result = res.response || {};
                // update the followings
                if (result.success && res.webInfo.requestId == uuid) {
                  _self
                    .$confirm("保存成功，是否需要返回列表？", "提示", {
                      confirmButtonText: "确定",
                      cancelButtonText: "取消",
                      type: "warning",
                    })
                    .then(() => {
                      _self.$router.push("/dictAdmin");
                    })
                    .catch(() => {
                      _self.loading = false;
                    });
                } else {
                  _self.loading = false;
                  _self.$message.error(result.msg || "新建失败");
                }
              });
            }
          } else if (this.$webview2.isWPF) {
            const uuid = this.$webview2.generateRandomUUID();
            await this.$webview2.sendWebView2(
              "/dictionaryParam/save",
              "post",
              "application/json;charset=UTF-8",
              form,
              false,
              uuid
            );
            await window.chrome.webview.addEventListener(
              "message",
              (e) => {
                let res = e.data;
                let result = res.response;
                // console.log(result);
                if (!result.success && res.response.uuid !== uuid) {
                  this.loading = false;
                  this.$message.error(result.msg || "新建失败");
                  return;
                }
                this.$confirm("保存成功，是否需要返回列表？", "提示", {
                  confirmButtonText: "确定",
                  cancelButtonText: "取消",
                  type: "warning",
                })
                  .then(() => {
                    this.$router.push("/dictAdmin");
                  })
                  .catch(() => {
                    this.loading = false;
                  });
              },
              {
                once: true,
              }
            );
          } else {
            request({
              url: "dictionaryParam/save", //接口
              method: "post",
              data: form,
            }).then((response) => {
              let result = response.data;
              // console.log(response)
              if (!result.success) {
                this.loading = false;
                this.$message.error(result.msg || "新建失败");
                return;
              }
              // this.fileName = form.fileName;
              // this.fileType = form.fileType;
              // this.fileDesc = form.fileDesc;
              this.$confirm("保存成功，是否需要返回列表？", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
              })
                .then(() => {
                  this.$router.push("/dictAdmin");
                })
                .catch(() => {
                  this.loading = false;
                });
              // _this.onSubmitFile(result.data.id);
            });
          }
        } else {
          return false;
        }
      });
    },
    onCancel() {
      this.form = {
        className: null,
        description: "",
        dirId: "",
        id: 0,
        methodName: null,
        number: 0,
        optCode: "",
        optName: "",
      };
      this.$router.push("/dictAdmin");
    },
  },
  created() {
    this.form.number = ++this.$store.state.dictAdmin.optionNumber;
    this.form.dirId = this.$store.state.dictAdmin.currentDirId;
    this.$store.commit("SET_BREADCRUMB", [
      { title: "字典管理", path: "/dictAdmin" },
      { title: "新增字典", path: "" },
    ]);
  },
};
</script>

<style scoped></style>
